#include "mprpcconfig.h"

#include <iostream>
#include <string>

void MprpcConfig::loadConfigFile(const char *configFile)
{
    FILE *fp = fopen(configFile, "r");
    if (fp == nullptr)
    {
        std::cout << configFile << " is not exist!" << std::endl;
        exit(EXIT_FAILURE);
    }

    while (!feof(fp))
    {
        char buf[256] = {0};
        fgets(buf, 256, fp);

        std::string src_buf(buf);
        Trim(src_buf);


        if (src_buf[0] == '#' || src_buf.empty())
        {
            continue;
        }

        std::string key;
        std::string value;

        std::size_t idx = src_buf.find('=');
        if (idx == std::string::npos)
        {
            // std::cout << "配置项不合法" << std::endl;
            continue;
        }
        key = src_buf.substr(0, idx);
        Trim(key);
        std::size_t endidx = src_buf.find('\n');
        value = src_buf.substr(idx + 1, endidx - idx-1);
        Trim(value);

        configMap_.insert({key, value});
    }
}
std::string MprpcConfig::load(std::string key)
{
    auto it = configMap_.find(key);
    if (it == configMap_.end())
    {
        return "";
    }
    return it->second;
}

void MprpcConfig::Trim(std::string &src_buf)
{
    std::size_t idx = src_buf.find_first_not_of(' ');
    if (idx != std::string::npos)
    {
        src_buf = src_buf.substr(idx, src_buf.size() - idx);
    }
    idx = src_buf.find_last_not_of(' ');
    if (idx != std::string::npos)
    {
        src_buf = src_buf.substr(0, idx + 1);
    }
}